package cn.kgc.tangcco.tcbd1011.no13.type.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.kgc.tangcco.tcbd1011.no13.base.util.JDBCUtils;
import cn.kgc.tangcco.tcbd1011.no13.type.dao.TypeDao;
import cn.kgc.tangcco.tcbd1011.no13.type.entity.Type;

public class TypeDaoImpl implements TypeDao {

	
	private QueryRunner qr;
	public TypeDaoImpl() {
		qr=new QueryRunner(JDBCUtils.getDataSource());
	}
	
	public int executeUpdate(String sql,Object...objects) {
		try {
			return qr.update(sql, objects);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	
	@Override
	public List<Type> queryAllType() {
		try {
			return qr.query("select * from type order by typeId desc", new BeanListHandler<>(Type.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Type detatilType(int pk) {
		try {
			return qr.query("select * from type where typeId=?", new BeanHandler<>(Type.class), pk);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int addType(Type type) {
		
		return this.executeUpdate("insert into type values(null,?)", type.getTypeName());
	}

	@Override
	public int updateType(Type type) {
		return this.executeUpdate("update type set typeName=? where typeId=?", type.getTypeName(),type.getTypeId());
	}

	@Override
	public int deleteType(int pk) {
		return this.executeUpdate("delete from type where typeId=?", pk);
	}

	@Override
	public int queryCountType() {
		try {
			return ((Long)qr.query("select count(*) from type", new ScalarHandler<>())).intValue();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

}
